package com.qs.eggs.utils;

import android.content.Context;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cookie.store.CookieStore;
import com.qs.eggs.Constants;

import java.net.URI;
import java.net.URL;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

/**
 * Created by Administrator on 2017/6/8.
 */

public class CookiesUtil {
    static CookieStore cookies= OkGo.getInstance().getCookieJar().getCookieStore();
    public static List<Cookie> cookies1= cookies.getCookie(HttpUrl.get(URI.create(Constants.URL_BASE+"mallLogin?action=checkMallLogin")));

    static String CookieName;
    public static String cookie;

    /**
     * 同步一下cookie
     */
    public static void syncCookie(Context context, String url){
        try{

            if(cookies1.size()!=0){
                CookieName=cookies1.get(0).name();
                cookie=cookies1.get(0).value();
            }else {
                Toast.makeText(context,"请先登录",Toast.LENGTH_SHORT).show();
                return;
            }
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            cookieManager.removeAllCookie();
            String oldCookie = cookieManager.getCookie(url);

            URL aURL = new URL(url);

            StringBuilder sbCookie = new StringBuilder();
            sbCookie.append(String.format(CookieName + "=%s",cookie));
            //webview在使用cookie前会前判断保存cookie的domain和当前要请求的domain是否相同，相同才会发送cookie
            sbCookie.append(String.format(";domain=%s",aURL.getHost())); //注意，是getHost()，不是getAuthority(),
            sbCookie.append(String.format(";path=%s","/"));

            String cookieValue = sbCookie.toString();
            cookieManager.setCookie(url, cookieValue);
            CookieSyncManager.getInstance().sync();

            String newCookie = cookieManager.getCookie(url);
        }catch(Exception e){
        }
    }
}
